// 点击新增按钮，弹出新增提醒事项窗口
import React, { useEffect } from 'react'
import moment from 'moment'
// keep-alive for React，Similar to Vue keep-alive, But it is not a component.
import useKeepState from 'use-keep-state'
import { Modal, Form, Input, DatePicker } from 'antd'
import {
  serviceCreateReminder,
  serviceUpdateReminder,
} from '../../../../request/reminder'
import { isBefore } from '../../../../utils/date'

const { TextArea } = Input
const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss'

type Props = {
  visible: boolean
  onCancel: () => void
  onSuccess: (res?: any) => void
  rowData?: { [key: string]: any }
}

interface State {
  confirmLoading: boolean
}

const initialState: State = {
  confirmLoading: false,
}

const CreateReminder: React.FC<Props> = function ({
  visible,
  rowData,
  onCancel,
  onSuccess,
}: Props) {
  const [form] = Form.useForm()
  const [state, setState] = useKeepState(initialState)

  async function handleSubmitForm() {
    try {
      const values = await form.validateFields()
      const params = {
        // values.date是Moment类型
        date: values.date.format(DATE_FORMAT),
        content: values.content.trim(),
      }
      setState({ confirmLoading: true })
      ;(!rowData
        ? serviceCreateReminder(params)
        : serviceUpdateReminder(rowData.id, params)
      )
        .then(res => {
          if (res.data.success) onSuccess(res)
        })
        .finally(() => {
          setState({ confirmLoading: false })
        })
    } catch {}
  }
  useEffect(() => {
    if (!visible) {
      form.resetFields()
    }
    if (visible && rowData) {
      form.setFieldsValue({
        date: moment(rowData.createdAt),
        content: rowData.content,
      })
    }
  }, [visible, rowData])

  return (
    <Modal
      title="新增"
      visible={visible}
      onOk={handleSubmitForm}
      onCancel={onCancel}
      confirmLoading={state.confirmLoading}
      maskClosable={false}
      forceRender
    >
      <Form form={form}>
        <Form.Item
          name="date"
          label="提醒时间"
          rules={[{ required: true, message: '请选择时间' }]}
        >
          {/* 不能选择今天之前的日期 */}
          <DatePicker
            showTime
            allowClear
            disabledDate={isBefore}
            style={{ width: '100%' }}
          ></DatePicker>
        </Form.Item>
        <Form.Item
          name="content"
          label="提醒内容"
          rules={[{ required: true, message: '请输入内容', whitespace: true }]}
        >
          <TextArea
            rows={3}
            maxLength={200}
            placeholder="请输入内容"
            allowClear
          ></TextArea>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default React.memo(CreateReminder)
